package com.zhuj.codec;

import com.zhuj.core.entity.ClientRequest;
import com.zhuj.core.entity.ServerResponse;
import com.zhuj.core.util.SerializerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by Administrator on 2018/1/8.
 */
public class NrpcProtostuffDecode extends ByteToMessageDecoder {

    private boolean sign;

    public NrpcProtostuffDecode(boolean sign){
        this.sign = sign;
    }

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        long a = System.currentTimeMillis();
        if (in.readableBytes() < 4) return;
        in.markReaderIndex();
        int len = in.readInt();
        if (in.readableBytes() < len) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[len];
        in.readBytes(data);
        if (sign)
            out.add(SerializerUtil.deserialize(data, ServerResponse.class));
        else
            out.add(SerializerUtil.deserialize(data, ClientRequest.class));
        System.out.println("解码毫秒数："+(System.currentTimeMillis()-a));
    }
}
